//! # SysY Compiler
//!
//! This is a SysY language compiler implementation that currently supports lexical analysis functionality.
//! SysY is a subset of the C language, commonly used for teaching compiler principles courses.
//!
//! # Usage
//!
//! ```bash
//! cargo run -- <source_file>
//! ```

mod lexer;
mod token;
mod util;

use crate::lexer::tokenize;
use log::debug;
use std::{env, fs};

fn main() {
    util::init_logger();
    debug!("log initialization to debug.log");

    let args: Vec<String> = env::args().collect();
    debug!("Command line arguments: {:?}", args);

    if args.len() < 2 {
        eprintln!("Usage: {} <filename>", args[0]);
        std::process::exit(1);
    }

    let filename = &args[1];
    debug!("Starting compiler with input file: {}", filename);

    let input = fs::read_to_string(filename).unwrap_or_else(|e| {
        eprintln!("Failed to read file {}: {}", filename, e);
        std::process::exit(1);
    });

    debug!("Input file read successfully, length = {}", input.len());

    debug!("Calling tokenize function...");
    let (tokens, errors) = tokenize(&input);
    debug!(
        "Tokenize function returned: {} tokens, {} errors",
        tokens.len(),
        errors.len()
    );

    if !errors.is_empty() {
        debug!("Processing {} errors", errors.len());
        for e in errors {
            eprintln!("{}", e);
        }
    } else {
        debug!("Processing {} tokens", tokens.len());
        for (token, line, text) in tokens {
            eprintln!("{} {} at Line {}.", token, text, line);
        }
    }

    debug!("Compiler execution completed");
}
